package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.zpmis.common.base.AdminLoginUser;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.enums.SequenceEnum;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.domain.enums.PurchaseEnum;
import org.zpmis.domain.purchase.model.Purchase;
import org.zpmis.domain.purchase.qo.AddPurchaseQo;
import org.zpmis.domain.purchase.qo.DelPurchaseQo;
import org.zpmis.domain.purchase.qo.EditPurchaseQo;
import org.zpmis.domain.purchase.qo.PurchaseListQo;
import org.zpmis.domain.purchase.service.PurchaseService;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.zpmis.domain.purchase.vo.PurchaseListVo;
import org.zpmis.domain.sequence.service.SequenceService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-6-2
 * Time: 14:54:17
 */
@Service
@Slf4j
public class PurchaseWebService extends BaseWebService {
     @Reference
     private PurchaseService purchaseService;

    @Reference
    private SequenceService sequenceService;

    /**
     * 新建采购订单
     * @param addPurchaseQo
     * @throws BusinessException
     * @throws Exception
     */
    public void addPurchase(AddPurchaseQo addPurchaseQo) throws BusinessException,Exception {
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        purchaseService.save(
        Purchase.builder()
                .code(sequenceService.getSequenceNum(SequenceEnum.PURCHASE))
                .name(addPurchaseQo.getName())
                .type(addPurchaseQo.getType())
                .repoId(addPurchaseQo.getRepoId())
                .total(addPurchaseQo.getTotal())
                .price(StringUtil.isEmpty(addPurchaseQo.getPrice()) ? BigDecimal.ZERO : new BigDecimal(addPurchaseQo.getPrice()).setScale(4))
                .attachment(addPurchaseQo.getAttachment())
                .status(addPurchaseQo.getStatus())
                .chargePerson(addPurchaseQo.getChargePerson())
                .purchaseTime(addPurchaseQo.getPurchaseTime())
                .createTime(Instant.now().toEpochMilli())
                .createId(adminLoginUser.getId())
                .createPerson(adminLoginUser.getUserName())
                .updateTime(Instant.now().toEpochMilli())
                .isDeleted(PurchaseEnum.NOT_DELETE.code())
                .build()
        );
    }

    /**
     * 修改采购单
     * @param editPurchaseQo
     * @throws BusinessException
     * @throws Exception
     */
    public void editPurchase(EditPurchaseQo editPurchaseQo) throws BusinessException,Exception {
        Long id = editPurchaseQo.getId();
        Purchase purchase = purchaseService.findById(id);
        if(purchase == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        purchase.setName(editPurchaseQo.getName());
        purchase.setType(editPurchaseQo.getType());
        purchase.setRepoId(editPurchaseQo.getRepoId());
        purchase.setTotal(editPurchaseQo.getTotal());
        purchase.setPrice(StringUtil.isEmpty(editPurchaseQo.getPrice()) ? BigDecimal.ZERO : new BigDecimal(editPurchaseQo.getPrice()).setScale(4));
        purchase.setAttachment(editPurchaseQo.getAttachment());
        purchase.setStatus(editPurchaseQo.getStatus());
        purchase.setChargePerson(editPurchaseQo.getChargePerson());
        purchase.setUpdateTime(Instant.now().toEpochMilli());
        purchaseService.update(purchase);
    }

    /**
     * 删除采购单
     * @param delPurchaseQo
     * @throws BusinessException
     * @throws Exception
     */
    public void delPurchase(DelPurchaseQo delPurchaseQo) throws BusinessException,Exception {
        Long id = delPurchaseQo.getId();
        Purchase purchase = purchaseService.findById(id);
        if(purchase == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        purchaseService.update(
        Purchase.builder()
                .id(id)
                .isDeleted(PurchaseEnum.DELETED.code())
                .updateTime(Instant.now().toEpochMilli())
                .build()
        );
    }

    /**
     * 采购单列表查询
     * @param purchaseListQo
     * @return
     * @throws BusinessException
     * @throws Exception
     */
    public PageInfo purchaseList(PurchaseListQo purchaseListQo) throws BusinessException,Exception {
        //获取当前登录用户
        AdminLoginUser adminLoginUser = super.getAdminLoginUser();
        if(adminLoginUser == null){
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        String name = purchaseListQo.getName();
        String code = purchaseListQo.getCode();
        Integer type = purchaseListQo.getType();
        Integer status = purchaseListQo.getStatus();
        String chargePerson = purchaseListQo.getChargePerson();
        Long startTime = purchaseListQo.getStartTime();
        Long endTime = purchaseListQo.getEndTime();
        Condition condition = new Condition(Purchase.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",PurchaseEnum.NOT_DELETE.code());

        if(StringUtil.isNotEmpty(code)){
            criteria.andLike("code","%"+code+"%");
        }
        if(StringUtil.isNotEmpty(name)){
            criteria.andLike("name","%"+name+"%");
        }
        if(StringUtil.isNotEmpty(chargePerson)){
            criteria.andLike("chargePerson","%"+chargePerson+"%");
        }
        if(type != null){
            criteria.andEqualTo("type",type);
        }
        if(status != null){
            criteria.andEqualTo("status",status);
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);
            criteria.andLessThanOrEqualTo("createTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("createTime",endTime);
        }
        condition.orderBy("createTime").desc();
        PageHelper.startPage(purchaseListQo.getPageNum(),purchaseListQo.getPageSize());
        List<Purchase> purchaseList = purchaseService.findByCondition(condition);
        PageInfo pageInfo = new PageInfo(purchaseList);
        List<PurchaseListVo> resultList = purchaseList.stream().map(PurchaseListVo::new).collect(Collectors.toList());
        //返回自定义实体对象
        pageInfo.setList(resultList);
        return pageInfo;
    }
}
